package com.ruoyi.mqtt.config;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;

// 1. 添加消息等待管理器
@Component
public class MqttResponseHolder {
    private final Map<String, CompletableFuture<String>> pendingRequests = new ConcurrentHashMap<>();
    private final AtomicLong timestampCounter = new AtomicLong(System.currentTimeMillis());


    public String createRequest() {
        String requestId = String.valueOf(timestampCounter.incrementAndGet());
        pendingRequests.put(requestId, new CompletableFuture<>());
        return requestId;
    }

    public void completeRequest(String requestId, String temperature) {
        CompletableFuture<String> future = pendingRequests.get(requestId);
        if (future != null) {
            future.complete(temperature);
            pendingRequests.remove(requestId);
        }
    }

    public String waitForResponse(String requestId, long timeout) throws TimeoutException {
        try {
            return pendingRequests.get(requestId).get(timeout, TimeUnit.SECONDS);
        } catch ( Exception e) {
            throw new RuntimeException(e);
        }
    }
}